﻿Imports System.IO
Imports System.ComponentModel
Imports MessageBoxEx
Imports System.Xml
Imports System.Collections.Specialized
Imports System.Text
Imports System.Text.RegularExpressions

Public Class frmMain
    Public defaultDemonbuddy As String = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Demonbuddy")
    Public defaultPatch As String = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Utilities")
    Public defaultItemRules As String = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Item Rules")
    Public defaultProfiles As String = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Profiles")
    Public defaultBackup As String = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Backups")
    Public defaultMods As String = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Mods")

    Public infoPatch() As xmlInformation
    Public infoMenu() As xmlInformation
    Public infoMod() As xmlInformation

    Public _triggerRefresh As Boolean = False
    Public _triggerReadMods As Boolean = False
    Public _triggerUpdate As Boolean = True
    Public _triggerCheckForMods As Boolean = False

    Public _textSubstitute As List(Of KeyValuePair(Of String, String)) = New List(Of KeyValuePair(Of String, String))

    Public _browseTarget As TextBox

    Public _tmpDir As String = Directory_ReturnTemp()

    Private _panelActive As Panel = panelModifications

    Private _pathDiablo As String
    Private _pathDemonbuddy As String

    Private _modIndex As Integer = Nothing

    Private _processingText As String = "Processing..."

    Private Delegate Sub backgroundRefresh()

    Private Sub Form_Menu_TriggerRoutine(ByVal sender As Object, ByVal e As EventArgs)

        Dim mnuSelected As ToolStripMenuItem = CType(sender, ToolStripDropDownItem)
        Dim mnuTag As String
        Dim mnuIndex As Integer

        Dim addonType As String
        Dim addonName As String
        Dim addonRootPath As String
        Dim addonPath As String
        Dim addonBackupPath As String = ""

        Dim svnResult As Boolean

        mnuTag = mnuSelected.Tag.ToString
        mnuIndex = Array_GetIDByValue(infoMenu, "menu-tag", mnuTag)

        addonType = Array_GetValueByTag(infoMenu, mnuIndex, "type")
        addonName = Array_GetValueByTag(infoMenu, mnuIndex, addonType & "-name")

        If URI_IsValid(mnuTag) = True Then

            Process.Start(mnuTag)
            Exit Sub

        End If

        If String_Equals(addonType, "Plugin") = True Then

            addonRootPath = My.Settings.FolderDemonbuddy & "\Plugins"
            addonPath = addonRootPath & "\" & Array_GetValueByTag(infoMenu, mnuIndex, addonType & "-folder-name")

            If Directory.Exists(My.Settings.FolderDemonbuddy & "\Plugins") = False Then

                Dim _Msg =
                        New MsgBoxEx(
                            "We could not locate your Demonbuddy plugin folder. Please verify your settings are correct.",
                            Me.Text, , MsgBoxExImage.Exclamation)
                _Msg.SetButtons(New String() {"OK"}, New DialogResult() {DialogResult.Yes}, 1)
                _Msg.ShowDialog(Me)

                frmSettings.Show()

                Exit Sub

            End If

            If Directory.Exists(addonPath) = True Then

                addonBackupPath = My.Settings.FolderBackup & "\DMA_Plugin_Backup_" & addonName

                If Directory.Exists(addonBackupPath) = True Then Directory.Delete(addonBackupPath, True)

                Directory.Move(addonPath, addonBackupPath)

            End If

            svnResult = SVN_CheckOut(New Uri(Array_GetValueByTag(infoMenu, mnuIndex, "svn")), addonPath)

            If svnResult = True Then

                Dim _Msg =
                        New MsgBoxEx(
                            "Successfully updated " & addonName & ". New version is [ " &
                            File_GetPluginVersion(addonPath) & " ].", Me.Text, , MsgBoxExImage.Information)
                _Msg.SetButtons(New String() {"OK"}, New DialogResult() {DialogResult.Yes}, 1)
                _Msg.ShowDialog(Me)

                If String_IsEmpty(addonBackupPath) = False Then Directory.Delete(addonBackupPath, True)

            Else

                Dim _Msg = New MsgBoxEx("Failure updating " & addonName & ". Reverting to previous version.", Me.Text, ,
                                        MsgBoxExImage.Exclamation)
                _Msg.SetButtons(New String() {"OK"}, New DialogResult() {DialogResult.Yes}, 1)
                _Msg.ShowDialog(Me)

                If String_IsEmpty(addonBackupPath) = False Then Directory.Move(addonBackupPath, addonPath)

            End If

        ElseIf String_Equals(addonType, "Profile") = True Then

            addonRootPath = My.Settings.FolderProfile
            addonPath = addonRootPath & "\" & Array_GetValueByTag(infoMenu, mnuIndex, addonType & "-folder-name")

            If Directory.Exists(My.Settings.FolderProfile) = False Then

                Dim _Msg =
                        New MsgBoxEx("We could not locate your profile folder. Please verify your settings are correct.",
                                     Me.Text, , MsgBoxExImage.Exclamation)
                _Msg.SetButtons(New String() {"OK"}, New DialogResult() {DialogResult.Yes}, 1)
                _Msg.ShowDialog(Me)

                frmSettings.Show()

                Exit Sub

            End If

            addonBackupPath = My.Settings.FolderBackup & "\DMA_Profile_Backup_" & addonName

            If Directory.Exists(addonBackupPath) = True Then Directory.Delete(addonBackupPath, True)

            If Directory.Exists(addonPath) Then Directory.Move(addonPath, addonBackupPath)

            svnResult = SVN_CheckOut(New Uri(Array_GetValueByTag(infoMenu, mnuIndex, "svn")), addonPath)

            If svnResult = True Then

                Dim _Msg =
                        New MsgBoxEx(
                            "Successfully updated " & addonType.ToLower & " """ & addonName & """ to revision [ " &
                            SVN_GetRevision(Array_GetValueByTag(infoMenu, mnuIndex, "svn")) & " ].", Me.Text, ,
                            MsgBoxExImage.Information)
                _Msg.SetButtons(New String() {"OK"}, New DialogResult() {DialogResult.Yes}, 1)
                _Msg.ShowDialog(Me)

                If Directory.Exists(addonBackupPath) = True Then Directory.Delete(addonBackupPath, True)

            Else

                Dim _Msg =
                        New MsgBoxEx(
                            "Failure updating " & addonType.ToLower & " """ & addonName &
                            """. Reverting to previous version.", Me.Text, , MsgBoxExImage.Exclamation)
                _Msg.SetButtons(New String() {"OK"}, New DialogResult() {DialogResult.Yes}, 1)
                _Msg.ShowDialog(Me)

                Directory.Move(addonBackupPath, addonPath)

            End If

        End If
    End Sub

    Public Sub DBMA_AfterWizard()

        Dim _checkout As Boolean
        Dim _svn As String = "http://dbma-mods.googlecode.com/svn/trunk/"

        If _triggerCheckForMods = False Then Exit Sub

        frmWizard.Hide()

        Me.Refresh()
        Me.Update()

        If (File.Exists(Path.Combine(My.Settings.FolderPatch, "patch.exe")) = False) Then

            Dim _MsgPatch =
                    New MsgBoxEx(
                        "Demonbuddy Modification Assistant needs to download a few files before you can actually patch anything. Would you like to download these files now?",
                        Me.Text, , MsgBoxExImage.Question)
            _MsgPatch.SetButtons(New String() {"Yes", "No"}, New DialogResult() {DialogResult.Yes, DialogResult.No}, 2)
            _MsgPatch.ShowDialog(Me)

            Dim _MsgPatchResult As DialogBoxResult = _MsgPatch.DialogBoxResult

            If _MsgPatchResult = DialogBoxResult.Button1 Then

                Dim dirPatch As String = My.Settings.FolderPatch
                Dim _result As Boolean = Download_PatchExe(dirPatch, progressbarextendedStatus)

                If _result Then

                    Dim _MsgOK = New MsgBoxEx("Download was successful.", Me.Text, , MsgBoxExImage.Check)
                    _MsgOK.SetButtons(New String() {"OK"},
                                      New System.Windows.Forms.DialogResult() {System.Windows.Forms.DialogResult.Yes}, 1)
                    _MsgOK.ShowDialog(Me)

                End If

            End If

        End If

        If (listviewextendedModifications.Items.Count = 0) Then

            Dim _MsgMods =
                    New MsgBoxEx(
                        "No modifications found. Would you like to download the default modifications for Demonbuddy Modification Asisstant?",
                        Me.Text, , MsgBoxExImage.Question)
            _MsgMods.SetButtons(New String() {"Yes", "No"}, New DialogResult() {DialogResult.Yes, DialogResult.No}, 2)
            _MsgMods.ShowDialog(Me)

            Dim _MsgModsResult As DialogBoxResult = _MsgMods.DialogBoxResult

            If _MsgModsResult = DialogBoxResult.Button1 Then

                Form_ProgressBar_Update("Downloading Modifications", 1, 0, 2)

                _checkout = SVN_CheckOut(New Uri(_svn), My.Settings.FolderMods(0))

                If _checkout = True Then

                    Form_ProgressBar_Update("Downloading Modifications (Complete)", 2, 0, 2)

                    Dim _MsgOK = New MsgBoxEx("Download was successful.", Me.Text, , MsgBoxExImage.Check)
                    _MsgOK.SetButtons(New String() {"OK"},
                                      New System.Windows.Forms.DialogResult() {System.Windows.Forms.DialogResult.Yes}, 1)
                    _MsgOK.ShowDialog(Me)

                    _triggerReadMods = True

                Else

                    Form_ProgressBar_Update("Downloading Modifications (Error)", 2, 0, 2)

                    Dim _MsgOK = New MsgBoxEx("There has been an error. Please try again later.", Me.Text, ,
                                              MsgBoxExImage.Exclamation)
                    _MsgOK.SetButtons(New String() {"OK"},
                                      New System.Windows.Forms.DialogResult() {System.Windows.Forms.DialogResult.Yes}, 1)
                    _MsgOK.ShowDialog(Me)

                End If

            End If

        End If

        If (File.Exists(Path.Combine(My.Settings.FolderDemonbuddy, "demonbuddy.exe")) = False) Then

            Dim _MsgDB =
                    New MsgBoxEx(
                        "Demonbuddy Modification Assistant recommends you download a fresh version of DemonbuddyBETA when patching. Would you like to do so now? Demonbuddy will be placed in the following location:" &
                        vbCrLf & vbCrLf & My.Settings.FolderDemonbuddy, Me.Text, , MsgBoxExImage.Question)
            _MsgDB.SetButtons(New String() {"Yes", "No"}, New DialogResult() {DialogResult.Yes, DialogResult.No}, 2)
            _MsgDB.ShowDialog(Me)

            Dim _MsgDBResult As DialogBoxResult = _MsgDB.DialogBoxResult

            If _MsgDBResult = DialogBoxResult.Button1 Then

                Dim _dbresult As Boolean = Download_DemonbuddyExe(My.Settings.FolderDemonbuddy,
                                                                  progressbarextendedStatus)

                If _dbresult = True Then

                    Dim _MsgOK = New MsgBoxEx("Download was successful.", Me.Text, , MsgBoxExImage.Check)
                    _MsgOK.SetButtons(New String() {"OK"},
                                      New System.Windows.Forms.DialogResult() {System.Windows.Forms.DialogResult.Yes}, 1)
                    _MsgOK.ShowDialog(Me)

                    _triggerReadMods = True

                Else

                    Dim _MsgOK = New MsgBoxEx("There has been an error. Please try again later.", Me.Text, ,
                                              MsgBoxExImage.Exclamation)
                    _MsgOK.SetButtons(New String() {"OK"},
                                      New System.Windows.Forms.DialogResult() {System.Windows.Forms.DialogResult.Yes}, 1)
                    _MsgOK.ShowDialog(Me)

                End If

            End If

        End If

        _pathDiablo = Path.Combine(My.Settings.FolderDiablo, "Diablo III.exe")
        _pathDemonbuddy = Path.Combine(My.Settings.FolderDemonbuddy, "Demonbuddy.exe")

        If File.Exists(_pathDiablo) Then
            buttonLaunchDiablo.Enabled = True
        Else
            buttonLaunchDiablo.Enabled = False
        End If


        If File.Exists(_pathDemonbuddy) Then
            buttonLaunchDemonbuddy.Enabled = True
        Else
            buttonLaunchDemonbuddy.Enabled = False
        End If

        _triggerRefresh = True

        timerProcessingText.Start()

    End Sub
    Public Function DBMA_Plugin_Download(ByVal svnPath As String, ByVal localPath As String,
                                         Optional enableBackup As Boolean = True)

        Dim folderName As String
        Dim addonBackupPath As String = ""

        Dim _result As Boolean

        folderName = Path.GetDirectoryName(svnPath)

        If Directory.Exists(localPath) = True Then

            If (enableBackup = True) Then

                addonBackupPath = My.Settings.FolderBackup & "\DMA_Plugin_Backup_" & folderName

                If Directory.Exists(addonBackupPath) = True Then Directory.Delete(addonBackupPath, True)

                Directory.Move(localPath, addonBackupPath)

            Else

                Dim _Msg =
                        New MsgBoxEx(
                            "We have found the directory you are updating to is not empty. How would you like to proceed?",
                            Me.Text, , MsgBoxExImage.Question)
                _Msg.SetButtons(New String() {"Overwrite", "Delete", "Cancel"},
                                New DialogResult() {DialogResult.Yes, DialogResult.No, DialogResult.Cancel}, 3)
                _Msg.ShowDialog(Me)

                Dim _msgResult As DialogBoxResult = _Msg.DialogBoxResult

                If _msgResult = DialogBoxResult.Button2 Then

                    Directory.Delete(localPath, True)

                ElseIf _msgResult = DialogBoxResult.Button3 Then

                    Return Nothing

                End If

            End If

        End If

        _result = SVN_CheckOut(New Uri(svnPath), localPath)

        If (_result) And (enableBackup) Then

            If String_IsEmpty(addonBackupPath) = False Then Directory.Delete(addonBackupPath, True)

        ElseIf Not (_result) And (enableBackup) Then

            If String_IsEmpty(addonBackupPath) = False Then Directory.Move(addonBackupPath, localPath)

        End If

        Return _result
    End Function

    Private Sub Form_Resize()

        Dim panelHeight As Integer = _panelActive.Height
        'Dim menuHeight As Integer = 52
        'Dim formBuffer As Integer = 16
        Dim formHeight As Integer
        Dim _panel As Control

        For Each _panel In Controls
            If TypeOf _panel Is Panel Then
                If Not (_panel Is _panelActive) Then
                    _panel.SendToBack()
                End If
            End If
        Next

        _panelActive.BringToFront()

        formHeight = panelHeight + 68 ' + menuHeight +  formBuffer

        Height = formHeight
    End Sub

    Private Sub Startup_FileSettings_Read()

        Dim i As Integer

        Dim xmlDocument As XmlDocument
        Dim xmlNodeList As XmlNodeList
        Dim xmlNode As XmlNode

        Dim _tag As String
        Dim _value As String

        _textSubstitute.Clear()

        _textSubstitute.Add(New KeyValuePair(Of String, String)("{demonbuddy-dir}", My.Settings.FolderDemonbuddy))
        _textSubstitute.Add(New KeyValuePair(Of String, String)("{profile-dir}", My.Settings.FolderProfile))
        _textSubstitute.Add(New KeyValuePair(Of String, String)("{itemrules-dir}", My.Settings.FolderItemRule))
        _textSubstitute.Add(New KeyValuePair(Of String, String)("{patch-dir}", My.Settings.FolderPatch))

        Dim fileSettings As String = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Settings.dms")

        If fileSettings = Nothing Then Exit Sub

        Try

            xmlDocument = New XmlDocument()
            xmlDocument.Load(fileSettings)
            xmlNodeList = xmlDocument.SelectNodes("/dbma/dbma_replacement_vars")

            For Each xmlNode In xmlNodeList

                For i = 0 To (xmlNode.ChildNodes.Count - 1)

                    _tag = xmlNode.ChildNodes.Item(i).LocalName
                    _value = xmlNode.ChildNodes.Item(i).InnerXml

                    _tag = "{" & _tag & "}"

                    _textSubstitute.Add(New KeyValuePair(Of String, String)(_tag, _value))

                Next

            Next xmlNode

        Catch errorVariable As Exception

        End Try
    End Sub

    Private Sub Form_ListView_SetHeaders()

        With listviewPatchList

            .BeginUpdate()

            .View = View.Details

            .Columns.Add("File Name")
            .Columns.Add("Type")
            .Columns.Add("Source (Original)").Width = 0
            .Columns.Add("Source (Modified)").Width = 0
            .Columns.Add("Target Path").Width = 0
            .Columns.Add("Target File").Width = 0
            .Columns.Add("MD5").Width = 0
            '---------------------
            .Columns.Add("Target")

            .EndUpdate()

        End With

        With listviewextendedModifications

            .View = View.Details

            .CheckBoxes = True
            .FullRowSelect = True
            .GridLines = True

            .Columns.Add("Modification Name")
            .Columns.Add("Type")
            .Columns.Add("Class")
            .Columns.Add("Author")
            .Columns.Add("Version")
            .Columns.Add("Patch Status")
            .Columns.Add("Update Status")

        End With

        With listviewDetails

            .View = View.Details

            .Columns.Add("Tag")
            .Columns.Add("Value")

        End With

        Form_ListView_AutoResize(listviewPatchList)
        Form_ListView_AutoResize(listviewDetails)
        Form_ListView_AutoResize(listviewextendedModifications)

    End Sub

    Private Sub Form_StartupRoutine()

        'Test MsgboxEx
        'Dim _Msg = New MsgBoxEx("Lorem Ipsum is simply dummy text of the printing and typesetting industry.", Me.Text)
        'Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like). Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
        'Dim _Msg = New MsgBoxEx("Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like). Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.", Me.Text, , MsgBoxExImage.Clock)
        '_Msg.checkboxText = "oiowefijqwoefjiqwopefjiopqwefjiopqwefjiqwopiefjopqweif"
        '_Msg.checkboxValue = True

        '_Msg.SetButtons(New String() {"Testing 123", "Testing 456", "Testing 789"}, New DialogResult() {DialogResult.Yes, DialogResult.No, DialogResult.Retry}, 3)
        '_Msg.ShowDialog(Me)

        'MsgBox(_Msg.DialogBoxResult)
        'MsgBox(_Msg.checkboxValue)

        My.Settings.FolderBackup = String.Empty
        My.Settings.FolderDemonbuddy = String.Empty
        My.Settings.FolderDiablo = String.Empty
        My.Settings.FolderItemRule = String.Empty
        My.Settings.FolderMods = New StringCollection()
        My.Settings.FolderPatch = String.Empty
        My.Settings.FolderProfile = String.Empty

        My.Settings.Save()

    End Sub

    Private Sub frmMain_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load

        Form_StartupRoutine()

        Startup_AppSettings_Read(True)

        Startup_FileSettings_Read()

        Form_ListView_SetHeaders()

        DBMA_Mods_Refresh()
        DBMA_Menus_Refresh()

        _panelActive = panelModifications

        Form_Resize()
    End Sub

    Public Sub DBMA_Refresh_All()

        DBMA_Mods_Refresh_Status()
        DBMA_Mods_Refresh_Update()
    End Sub

    Public Sub DBMA_Mods_Refresh()

        DBMA_Mods_Clear()
        DBMA_Mods_Read()
        DBMA_Mods_Add()
    End Sub

    Public Sub DBMA_Menus_Refresh()

        DBMA_Menus_Clear()
        DBMA_Menus_Read()
        DBMA_Menus_Add()
    End Sub

    Private Sub DBMA_Mods_Add()

        Dim patchCount As Integer
        Dim patchCur As Integer
        Dim _data(6) As String
        Dim _item As ListViewItem

        patchCount = Array_GetMaxIndex(infoPatch)

        If (patchCount = 0) Then Exit Sub
        listviewextendedModifications.BeginUpdate()

        For patchCur = 0 To patchCount

            _data(0) = Array_GetValueByTag(infoPatch, patchCur, "addon-title")
            _data(1) = Array_GetValueByTag(infoPatch, patchCur, "addon-type")
            _data(2) = Array_GetValueByTag(infoPatch, patchCur, "addon-class")
            _data(3) = Array_GetValueByTag(infoPatch, patchCur, "addon-author")
            _data(4) = Array_GetValueByTag(infoPatch, patchCur, "addon-version")
            _data(5) = _processingText
            _data(6) = _processingText

            _item = New ListViewItem(_data)

            _item.UseItemStyleForSubItems = False

            _item.SubItems(5).ForeColor = Color.DarkBlue 'Update
            _item.SubItems(6).ForeColor = Color.DarkRed 'Status

            listviewextendedModifications.Items.Add(_item)

        Next

        Form_ListView_AutoResize(listviewextendedModifications)

        listviewextendedModifications.EndUpdate()

        timerProcessingText.Start()
    End Sub

    Private Function DBMA_Mod_Update(ByVal patch As Integer?) As Boolean

        Dim _svnPath As String = Array_GetValueByTag(infoPatch, patch, "addon-svn")
        Dim _localPath As String = Array_GetValueByTag(infoPatch, patch, "path")
        Dim _downloadPath As String = Directory_ReturnTemp()

        If String_IsEmpty(patch) Then Return Nothing
        If String_IsEmpty(_svnPath) Then Return Nothing
        If String_IsEmpty(_localPath) Then Return Nothing

        Application.DoEvents()

        Dim _svnResult As Boolean = SVN_CheckOut(New Uri(_svnPath), _downloadPath)

        If _svnResult = True Then

            Directory.Delete(_localPath, True)
            Directory.Move(_downloadPath, _localPath)

            Return True

        End If

        Return False
    End Function

    Private Function DBMA_Mod_Refresh_Update(ByVal patch As Integer?) As en_resultUpdateCheck

        If (patch Is Nothing) Then Return en_resultUpdateCheck.UnknownError

        Dim _svnPath As String = Array_GetValueByTag(infoPatch, patch, "addon-svn")
        Dim _downloadPath As String = Directory_ReturnTemp()
        Dim _file As String()
        Dim _updateCheck As String
        Dim _array() As xmlInformation = Nothing
        Dim _result As versionResult
        'Dim _localPath As String = Array_GetValueByTag(infoPatch, patch, "path")

        If String_IsEmpty(_svnPath) = True Then Return en_resultUpdateCheck.NoSvnPath

        Application.DoEvents()

        _updateCheck = Array_GetValueByTag(infoPatch, patch, "status-update")

        If String_IsEmpty(_updateCheck) Then

            Dim _svnResult As Boolean = SVN_CheckOut(New Uri(_svnPath), _downloadPath)

            If _svnResult = True Then

                _file = Directory.GetFiles(_downloadPath, "*.dma", SearchOption.TopDirectoryOnly)

                If _file.Count = 0 Or _file.Count > 1 Then Return False

                XML_ReadPatchData(_file(0), _array)

                _updateCheck = Version_Compare(Array_GetValueByTag(infoPatch, patch, "addon-version"),
                                               Array_GetValueByTag(_array, 0, "addon-version"))

            End If

            If Directory.Exists(_downloadPath) Then Directory.Delete(_downloadPath, True)

        End If

        If String_IsEmpty(_updateCheck) Then

            Dim _Msg = New MsgBoxEx("Error downloading from SVN. Please try again later.", Me.Text, ,
                                    MsgBoxExImage.Exclamation)
            _Msg.SetButtons(New String() {"OK"}, New DialogResult() {DialogResult.Yes}, 1)
            _Msg.ShowDialog(Me)

            Dim _msgResult As DialogBoxResult = _Msg.DialogBoxResult

            Return en_resultUpdateCheck.UnknownError

        End If

        _result = CType(_updateCheck, versionResult)

        If _result = versionResult.IsNewer Then

            Return en_resultUpdateCheck.UpdateAvailable

        End If

        Return en_resultUpdateCheck.UpToDate
    End Function

    Public Function DBMA_Mod_Refresh_Status(ByVal patch As Integer?, Optional optRefresh As Boolean = True,
                                            Optional optFixPath As Boolean = True) As String

        If (patch Is Nothing) Then Return "No Patch Found"

        Dim _count As Integer = Array_GetPatchCount(infoPatch, patch)
        Dim _result(_count - 1) As en_resultPatch
        Dim _return As String

        If (_count = 0) Then Return "No Patch Found"

        For _index As Integer = 0 To (_count - 1)

            Dim _tmp As String = Nothing

            If (optRefresh = False) Then _tmp = Array_GetValueByTag(infoPatch, patch, "status-" & _index)

            If (_tmp Is Nothing) Then

                Dim _pathDiff As String = Array_GetValueByTag(infoPatch, patch, "path")
                Dim _fileDiff As String = Array_GetValueByTag(infoPatch, patch, "patch" & _index & "-diff")

                Dim _pathTarget As String = Array_GetValueByTag(infoPatch, patch, "patch" & _index & "-location",
                                                                _textSubstitute)
                Dim _fileTarget As String = Array_GetValueByTag(infoPatch, patch, "patch" & _index & "-file",
                                                                _textSubstitute)

                Dim _diff As String = Path.Combine(_pathDiff, _fileDiff)
                Dim _target As String = Path.Combine(_pathTarget, _fileTarget)

                If (optFixPath) Then

                    _diff = File_FixPath(_diff, False)
                    _target = File_FixPath(_target, True, My.Settings.FolderDemonbuddy)

                End If

                _tmp = Diff_Execute(_diff, _target, True)

                Array_SetValueByTag(infoPatch, patch, "status-" & _index, _tmp)

                _result(_index) = _tmp

            End If

        Next

        _return = Diff_InterpretStatus(infoPatch, patch)

        If (_return Is Nothing) Then Return "No Return Found"

        Return _return
    End Function

    Private Sub DBMA_GetPaths(ByVal searchPattern As String, ByRef _return As List(Of String))

        Dim _settingsPaths(My.Settings.FolderMods.Count - 1) As String
        Dim _files As String()
        Dim _index As Integer
        Dim _file As Integer

        My.Settings.FolderMods.CopyTo(_settingsPaths, 0)

        For _index = 0 To (_settingsPaths.Count - 1)

            If (Directory.Exists(_settingsPaths(_index)) = True) Then

                _files = Directory.GetFiles(_settingsPaths(_index), searchPattern, SearchOption.AllDirectories)

                Console.WriteLine("Found " & _files.Count & " Mods...")

                For _file = 0 To (_files.Count - 1)

                    _return.Add(_files(_file))

                Next

            End If

        Next
    End Sub

    Private Sub DBMA_Menus_Clear()

        Dim mnuPlugins As ToolStripMenuItem
        Dim mnuProfiles As ToolStripMenuItem

        Erase infoMenu

        mnuPlugins = menuUpdatePlugin
        mnuProfiles = menuUpdateProfile

        mnuPlugins.DropDownItems.Clear()
        mnuProfiles.DropDownItems.Clear()
    End Sub

    Private Sub DBMA_Menus_Add()

        Dim i As Integer

        Dim mnuName As String
        Dim mnuDesc As String
        Dim mnuType As String
        Dim mnuTag As String
        Dim mnuAuthor As String
        Dim mnuItem As ToolStripMenuItem

        Dim submenuItem As ToolStripMenuItem
        Dim submenuAuthorURI As String
        Dim submenuDonateURI As String

        'Dim addonVersion As String

        If (infoMenu Is Nothing) Then Exit Sub
        For i = 0 To Array_GetMaxIndex(infoMenu)

            mnuItem = New ToolStripMenuItem()

            mnuType = Array_GetValueByTag(infoMenu, i, "type")

            mnuName = Array_GetValueByTag(infoMenu, i, "menu-name")
            mnuDesc = Array_GetValueByTag(infoMenu, i, "menu-desc")
            mnuTag = Array_GetValueByTag(infoMenu, i, "menu-tag")

            mnuAuthor = Array_GetValueByTag(infoMenu, i, mnuType & "-author")
            'addonVersion = Array_GetValueByTag(infoMenu, i, "addon-version")

            mnuItem.Text = mnuName & " (by " & mnuAuthor & ")"
            mnuItem.ToolTipText = mnuDesc

            If mnuType.ToLower = "plugin" Then
                menuUpdatePlugin.DropDownItems.Add(mnuItem)
            ElseIf mnuType.ToLower = "profile" Then
                menuUpdateProfile.DropDownItems.Add(mnuItem)
            End If

            submenuAuthorURI = Array_GetValueByTag(infoMenu, i, mnuType & "-author_url")
            submenuDonateURI = Array_GetValueByTag(infoMenu, i, mnuType & "-donation_url")

            submenuItem = Menu_CreateSubMenu("Download/Update", mnuTag, mnuDesc)

            mnuItem.DropDownItems.Add(submenuItem)

            AddHandler submenuItem.Click, AddressOf Form_Menu_TriggerRoutine

            mnuItem.DropDownItems.Add("-")

            If String_IsEmpty(submenuAuthorURI) = False Then
                submenuItem = Menu_CreateSubMenu("Authors Website", submenuAuthorURI,
                                                 "Click here to goto the website of this " & mnuType & "s author.", True)
                mnuItem.DropDownItems.Add(submenuItem)
                AddHandler submenuItem.Click, AddressOf Form_Menu_TriggerRoutine
            End If

            If String_IsEmpty(submenuDonateURI) = False Then
                submenuItem = Menu_CreateSubMenu("Donate To Author", submenuDonateURI,
                                                 "Click here to donate to this " & mnuType & "s author.", True)
                mnuItem.DropDownItems.Add(submenuItem)
                AddHandler submenuItem.Click, AddressOf Form_Menu_TriggerRoutine
            End If

        Next

        Form_ListView_AutoResize(listviewextendedModifications)
    End Sub

    Private Sub DBMA_Menus_Read()

        Dim _pathMod As New List(Of String)

        DBMA_GetPaths("*.dmm", _pathMod)

        For i As Integer = 0 To (_pathMod.Count - 1)

            XML_ReadMenuData(_pathMod.Item(i), infoMenu, i, True)

        Next
    End Sub

    Private Sub DBMA_Mods_Clear()

        Erase infoPatch

        listviewextendedModifications.Items.Clear()
        listviewDetails.Items.Clear()
        textboxDescription.Clear()
    End Sub

    Private Sub DBMA_Mods_Read()

        Dim _pathMod As New List(Of String)

        DBMA_GetPaths("*.dma", _pathMod)

        For i As Integer = 0 To (_pathMod.Count - 1)

            XML_ReadPatchData(_pathMod.Item(i), infoPatch, i, True, True)

        Next
    End Sub

    Private Sub menuSettings_Click(ByVal sender As Object, ByVal e As EventArgs) Handles menuSettings.Click

        frmSettings.Show()
    End Sub

    Public Sub Startup_AppSettings_Read(Optional ByVal bStartup As Boolean = False)

StartOver:
        Dim _utilities As String = My.Settings.FolderPatch
        Dim _backup As String = My.Settings.FolderBackup
        Dim _profile As String = My.Settings.FolderProfile
        Dim _itemrules As String = My.Settings.FolderItemRule
        Dim boolDefault As Boolean =
                (String_IsEmpty(_backup) Or String_IsEmpty(_utilities) Or String_IsEmpty(_profile) Or
                 String_IsEmpty(_itemrules))

        buttonLaunchDiablo.Enabled = False
        buttonLaunchDemonbuddy.Enabled = False

        If (bStartup = True) And (boolDefault = True) Then

            frmWizard.Show()
            Me.Enabled = False

        End If

    End Sub

    Private Sub buttonLaunchDiablo_Click(ByVal sender As Object, ByVal e As EventArgs) Handles buttonLaunchDiablo.Click

        Dim _path As String

        _path = Path.Combine(My.Settings.FolderDiablo, "Diablo III.exe")

        If Process_Launch(_path) = False Then

            Dim _MsgLaunch = New MsgBoxEx("Error Launching Diablo III. Please check your settings.", Me.Text, ,
                                          MsgBoxExImage.Exclamation)
            _MsgLaunch.SetButtons(New String() {"OK"},
                                  New System.Windows.Forms.DialogResult() {System.Windows.Forms.DialogResult.Yes}, 1)
            _MsgLaunch.ShowDialog(Me)

        End If
    End Sub

    Private Sub buttonLaunchDemonbuddy_Click(ByVal sender As Object, ByVal e As EventArgs) _
        Handles buttonLaunchDemonbuddy.Click

        Dim _path As String

        _path = Path.Combine(My.Settings.FolderDemonbuddy, "Demonbuddy.exe")

        If Process_Launch(_path) = False Then

            Dim _MsgLaunch = New MsgBoxEx("Error Launching Demonbuddy. Please check your settings.", Me.Text, ,
                                          MsgBoxExImage.Exclamation)
            _MsgLaunch.SetButtons(New String() {"OK"},
                                  New System.Windows.Forms.DialogResult() {System.Windows.Forms.DialogResult.Yes}, 1)
            _MsgLaunch.ShowDialog(Me)

        End If
    End Sub

    Private Sub listviewextendedModifications_ItemCheck(sender As Object, e As ItemCheckEventArgs) _
        Handles listviewextendedModifications.ItemCheck

        If listviewextendedModifications.Items(e.Index).Tag = String.Empty Then

            listviewextendedModifications.Items(e.Index).Checked = False

        End If
    End Sub

    Private Sub listviewextendedModifications_MouseDown(sender As Object, e As MouseEventArgs) _
        Handles listviewextendedModifications.MouseDown

        Dim _position As Point = listviewextendedModifications.PointToClient(MousePosition)
        Dim _test As ListViewHitTestInfo = listviewextendedModifications.HitTest(_position)

        menuApplyMod.Visible = False
        menuUpdateMod.Visible = False
        menuRightClickDash.Visible = False

        If (_test.SubItem Is Nothing) Then Exit Sub

        If (e.Button = MouseButtons.Right) Then

            Dim _row As Integer = _test.Item.Index

            Dim _patchName As String = listviewextendedModifications.Items(_row).SubItems(0).Text
            Dim _patchIndex As Integer = Array_GetIDByValue(infoPatch, "addon-title", _patchName)

            If (_patchIndex = Nothing) Then Exit Sub

            _modIndex = _row

            Dim _subitemUpdateText As String = listviewextendedModifications.Items(_row).SubItems(6).Text
            Dim _subitemStatusText As String = listviewextendedModifications.Items(_row).SubItems(5).Text

            If _subitemUpdateText.Contains("Update") Then
                menuUpdateMod.Visible = True
                menuRightClickDash.Visible = True
            Else
                menuUpdateMod.Visible = False
            End If

            If (Strings.Left(_subitemStatusText, 5) = "Ready") Then
                menuApplyMod.Visible = True
                menuRightClickDash.Visible = True
            Else
                menuApplyMod.Visible = False
            End If

        End If
    End Sub

    Private Sub listviewextendedModifications_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) _
        Handles listviewextendedModifications.SelectedIndexChanged

        Dim _items As ListView.SelectedListViewItemCollection = CType(sender, ListViewExtended).SelectedItems
        Dim _item As ListViewItem

        Dim _patchName As String
        Dim _patchID As Integer

        Dim _tag As String
        Dim _value As String

        For Each _item In _items

            _patchName = _item.SubItems(0).Text
            _patchID = Array_GetIDByValue(infoPatch, "addon-title", _patchName)

            If _patchID > -1 Then

                listviewDetails.Items.Clear()

                listviewDetails.BeginUpdate()

                For i As Integer = 0 To (infoPatch.Count - 1)

                    If (infoPatch(i).idx = _patchID) Then

                        _tag = infoPatch(i).tag
                        _value = infoPatch(i).value

                        If _tag.ToLower = "addon-description" Then

                            textboxDescription.Text = _value

                        End If

                        Dim _detail As ListViewItem = New ListViewItem(New String() {_tag, _value})

                        listviewDetails.Items.Add(_detail)

                    End If

                Next

                listviewDetails.EndUpdate()

            End If

        Next

        Form_ListView_AutoResize(listviewDetails)
    End Sub

    Private Sub buttonApply_Click(ByVal sender As Object, ByVal e As EventArgs) Handles buttonApply.Click

        Dim i As Integer

        Dim _fileTarget As String
        Dim _fileDiff As String
        Dim _tmpLines As String
        Dim curLines As List(Of String) = Nothing

        Dim _tmpPath As String
        Dim _tmpDiff As String
        Dim _tmpTargetLocation As String
        Dim _tmpTargetFileName As String

        Console.WriteLine(" --- Starting Patching Routine")

        For i = 0 To (listviewextendedModifications.Items.Count - 1)

            Form_ProgressBar_Update(
                "Applying Modifications (" & (i + 1) & "/" & listviewextendedModifications.Items.Count & ")...", i, 0,
                (listviewextendedModifications.Items.Count - 1))

            If listviewextendedModifications.Items(i).Checked = True Then

                Dim patchCount As Integer = Array_GetPatchCount(infoPatch, i)

                Dim patchResult(patchCount - 1) As en_resultPatch

                For patchCur As Integer = 0 To (patchCount - 1)

                    Form_ProgressBar_Update("Applying Patch (" & (patchCur + 1) & "/" & patchCount & ")...", patchCur, 0,
                                            (patchCount - 1))

                    _tmpPath = Array_GetValueByTag(infoPatch, i, "path")
                    _tmpDiff = Array_GetValueByTag(infoPatch, i, "patch" & patchCur & "-diff")
                    _tmpTargetLocation = Array_GetValueByTag(infoPatch, i, "patch" & patchCur & "-location",
                                                             _textSubstitute)
                    _tmpTargetFileName = Array_GetValueByTag(infoPatch, i, "patch" & patchCur & "-file")

                    _fileDiff = File_FixPath(Path.Combine(_tmpPath, _tmpDiff), False)
                    _fileTarget = File_FixPath(Path.Combine(_tmpTargetLocation, _tmpTargetFileName), True,
                                               My.Settings.FolderDemonbuddy)

                    _tmpLines = Array_GetValueByTag(infoPatch, i, "patch" & patchCur & "-line")

                    If File.Exists(_fileDiff) = False Then

                        Console.WriteLine("Could not find patch file: " & _fileDiff & "...")

                        GoTo NextFor

                    Else

                        Console.WriteLine("Found patch file: " & Path.GetFileName(_fileDiff) & "...")

                    End If

                    If File.Exists(_fileTarget) = False Then

                        Console.WriteLine("Could not find target file: " & _fileTarget & "...")

                        GoTo NextFor

                    Else

                        Console.WriteLine("Found patch target: " & Path.GetFileName(_fileTarget) & "...")

                    End If

                    If String_IsEmpty(_tmpLines) = False Then

                        If _tmpLines.Contains(",") Then

                            curLines = _tmpLines.Split(",").ToList()
                            Console.WriteLine("Found " & curLines.Count & " Hunk/s For Verification...")

                        ElseIf IsNumeric(_tmpLines) = True Then

                            curLines.Add(_tmpLines)
                            Console.WriteLine("Found 1 Hunk/s For Verification...")

                        End If

                    End If

                    patchResult(patchCur) = Diff_Execute(_fileDiff, _fileTarget, False)

                    Array_SetValueByTag(infoPatch, i, "status-" & patchCur, patchResult(patchCur))

                    If (patchResult(patchCur) = en_resultPatch.ExeNotFound) Then

                        Console.WriteLine("The executable for patch.exe could not be found.")

                    ElseIf patchResult(patchCur) = en_resultPatch.AlreadyPatched Then

                        Console.WriteLine("""" & _fileDiff & """ has already been applied to """ & _fileTarget & """")

                    ElseIf patchResult(patchCur) = en_resultPatch.Failure Then

                        Console.WriteLine("""" & _fileDiff & """ failed patching """ & _fileTarget & """")

                    ElseIf patchResult(patchCur) = en_resultPatch.TargetNotFound Then

                        Console.WriteLine("""" & _fileDiff & """ could not find """ & _fileTarget & """")

                    ElseIf patchResult(patchCur) = en_resultPatch.Success Then

                        Console.WriteLine("""" & _fileDiff & """ successfully patched """ & _fileTarget & """")

                    ElseIf patchResult(patchCur) = en_resultPatch.SuccessWithChanges Then

                        Console.WriteLine("""" & _fileDiff & """ successfully (fuzzy) patched """ & _fileTarget & """")

                    ElseIf patchResult(patchCur) = en_resultPatch.Unknown Then

                        Console.WriteLine("""" & _fileDiff & """ had an unknown error patching """ & _fileTarget & """")

                    End If

                Next

            End If
NextFor:
        Next

        Form_ProgressBar_Update("Applying Modifications (Complete)", 0, 0, 1)

        _triggerReadMods = True

        timerProcessingText.Start()

        Console.WriteLine(" --- Patching Routine (Complete)")
    End Sub

    Private Sub buttonRestore_Click(ByVal sender As Object, ByVal e As EventArgs) Handles buttonRestore.Click

        frmRestore.Show()

        frmRestore.Restore_Refresh()
    End Sub

    Private Sub buttonBackup_Click(ByVal sender As Object, ByVal e As EventArgs) Handles buttonBackup.Click

        buttonBackup.Enabled = False

        Backup_Folder(My.Settings.FolderDemonbuddy, My.Settings.FolderBackup, False, False)

        buttonBackup.Enabled = True
    End Sub

    Private Sub buttonSave_Click(ByVal sender As Object, ByVal e As EventArgs) Handles buttonSave.Click

        Dim dialog As String = Dialog_SaveFile(True, "Save Menu As", "dmm", "DBMA Menu (*.dmm)|*.dmm",
                                               Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory))

        If dialog = Nothing Then Exit Sub

        Dim xmlWriter As New XmlTextWriter(dialog, Encoding.UTF8)

        Dim radioButton As RadioButton =
                groupboxMenuContentType.Controls.OfType(Of RadioButton)().Where(Function(r) r.Checked = True).
                FirstOrDefault()
        Dim menuType As String = radioButton.Text.ToLower
        Dim menuTag As String =
                Regex.Replace("menu" & textboxCName.Text & textboxAVersion.Text, "^[a-zA-Z0-9]+$ ", "").ToLower

        xmlWriter.WriteStartDocument(True)
        xmlWriter.Formatting = Formatting.Indented
        xmlWriter.Indentation = 2
        xmlWriter.WriteStartElement("menu_info")
        xmlWriter.WriteStartElement("menu")
        XML_CreateNode(xmlWriter, "menu-name", textboxCName.Text)
        XML_CreateNode(xmlWriter, "menu-tag", menuTag)
        XML_CreateNode(xmlWriter, "menu-desc", textboxCDescription.Text)
        XML_CreateNode(xmlWriter, "addon-version", textboxAVersion.Text)
        XML_CreateNode(xmlWriter, "addon-author", textboxAAuthor.Text)
        XML_CreateNode(xmlWriter, "addon-author_url", textboxAURL.Text.ToLower)
        XML_CreateNode(xmlWriter, "svn", textboxCSVN.Text.ToLower)
        XML_CreateNode(xmlWriter, "type", menuType)
        XML_CreateNode(xmlWriter, menuType & "-name", textboxCName.Text)
        XML_CreateNode(xmlWriter, menuType & "-desc", textboxCContentDescription.Text)
        XML_CreateNode(xmlWriter, menuType & "-author", textboxCAuthor.Text)
        XML_CreateNode(xmlWriter, menuType & "-author_url", textboxCAuthorURL.Text.ToLower)
        XML_CreateNode(xmlWriter, menuType & "-donation_url", textboxCDonateURL.Text.ToLower)
        XML_CreateNode(xmlWriter, menuType & "-folder-name", textboxCFolderName.Text)
        XML_CreateNode(xmlWriter, menuType & "-folder-location", textboxCFolderLocation.Text)
        xmlWriter.WriteEndElement() 'menu
        xmlWriter.WriteEndElement() 'menu-info
        xmlWriter.WriteEndDocument()
        xmlWriter.Close()

        Dim _Msg = New MsgBoxEx("Menu saved.", Me.Text, , MsgBoxExImage.Information)
        _Msg.SetButtons(New String() {"OK"}, New DialogResult() {DialogResult.Yes}, 1)
        _Msg.ShowDialog(Me)

        _panelActive = panelModifications

        Form_Resize()
    End Sub

    Private Sub submenuShowMenuGenerator_Click(ByVal sender As Object, ByVal e As EventArgs) _
        Handles submenuShowMenuGenerator.Click

        _panelActive = panelGenerateMenu

        Form_Resize()
    End Sub

    Private Sub submenuShowModifications_Click(ByVal sender As Object, ByVal e As EventArgs) _
        Handles submenuShowModifications.Click

        _panelActive = panelModifications

        Form_Resize()
    End Sub

    Private Sub buttonOpen_Click(ByVal sender As Object, ByVal e As EventArgs) Handles buttonOpen.Click

        Dim dialog As String = Dialog_OpenFile("Open Menu", "dmm", "DBMA Menu (*.dmm)|*.dmm",
                                               Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory))

        Dim _array(0) As xmlInformation

        Dim menuType As String

        If dialog = Nothing Then Exit Sub

        XML_ReadMenuData(dialog, _array, , False)

        If _array Is Nothing Then Return

        menuType = Array_GetValueByTag(_array, 0, "type")

        radioMTPlugin.Checked = False
        radioMTProfile.Checked = False
        radioMTModification.Checked = False
        radioMTCustom.Checked = False

        If menuType.ToLower = "plugin" Then
            radioMTPlugin.Checked = True
        ElseIf menuType.ToLower = "profile" Then
            radioMTProfile.Checked = True
        ElseIf menuType.ToLower = "modification" Then
            radioMTModification.Checked = True
        ElseIf menuType.ToLower = "custom" Then
            radioMTCustom.Checked = True
        End If

        textboxAVersion.Text = Array_GetValueByTag(_array, 0, "addon-version")
        textboxAAuthor.Text = Array_GetValueByTag(_array, 0, "addon-author")
        textboxAURL.Text = Array_GetValueByTag(_array, 0, "addon-author_url")
        textboxCDescription.Text = Array_GetValueByTag(_array, 0, "menu-desc")
        textboxCSVN.Text = Array_GetValueByTag(_array, 0, "svn")
        textboxCName.Text = Array_GetValueByTag(_array, 0, menuType & "-name")
        textboxCContentDescription.Text = Array_GetValueByTag(_array, 0, menuType & "-desc")
        textboxCAuthor.Text = Array_GetValueByTag(_array, 0, menuType & "-author")
        textboxCAuthorURL.Text = Array_GetValueByTag(_array, 0, menuType & "-author_url")
        textboxCDonateURL.Text = Array_GetValueByTag(_array, 0, menuType & "-donation_url")
        textboxCFolderName.Text = Array_GetValueByTag(_array, 0, menuType & "-folder-name")
        textboxCFolderLocation.Text = Array_GetValueByTag(_array, 0, menuType & "-folder-location")
    End Sub

    Private Sub contextmenuTBFDemonbuddy_Click(ByVal sender As Object, ByVal e As EventArgs) _
        Handles contextmenuTBFDemonbuddy.Click

        _browseTarget.Text = "{demonbuddy-dir}"
    End Sub

    Private Sub contextmenuTBFPlugin_Click(ByVal sender As Object, ByVal e As EventArgs) _
        Handles contextmenuTBFPlugin.Click

        _browseTarget.Text = "{demonbuddy-dir}\Plugins\"
    End Sub

    Private Sub contextmenuTBFProfile_Click(ByVal sender As Object, ByVal e As EventArgs) _
        Handles contextmenuTBFProfile.Click

        _browseTarget.Text = "{profile-dir}"
    End Sub

    Private Sub buttonModificationOpen_Click(ByVal sender As Object, ByVal e As EventArgs) _
        Handles buttonModificationOpen.Click

        Dim dialog As String = Dialog_OpenFile("Open Patch", "dma", "DBMA Patch (*.dma)|*.dma",
                                               Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory))

        Dim _count As String

        Dim _fileDiff As String
        Dim _pathDiff As String
        Dim _addonType As String
        Dim _fileTarget As String
        Dim _info As xmlInformation() = Nothing

        Dim _data(7) As String
        Dim _item As ListViewItem

        If dialog = Nothing Then Exit Sub

        XML_ReadPatchData(dialog, _info, 0, False, True)

        If _info Is Nothing Then Return

        listviewPatchList.Items.Clear()
        infoMod = _info

        If _tmpDir Is Nothing Then _tmpDir = Directory_ReturnTemp()

        _addonType = Array_GetValueByTag(infoMod, 0, "addon-type")

        textboxPatchTitle.Text = Array_GetValueByTag(infoMod, 0, "addon-title")
        textboxPatchDescription.Text = Array_GetValueByTag(infoMod, 0, "addon-description")
        comboboxSubtype.Text = Array_GetValueByTag(infoMod, 0, "addon-subtype")
        comboboxTargetClass.Text = Array_GetValueByTag(infoMod, 0, "addon-class")
        textboxPatchVersion.Text = Array_GetValueByTag(infoMod, 0, "addon-version")
        textboxPatchAuthor.Text = Array_GetValueByTag(infoMod, 0, "addon-author")
        textboxPatchAuthorURL.Text = Array_GetValueByTag(infoMod, 0, "addon-author_url")
        textboxPatchSVN.Text = Array_GetValueByTag(infoMod, 0, "addon-svn")
        textboxTargetName.Text = Array_GetValueByTag(infoMod, 0, _addonType & "-name")
        textboxTargetVersionMin.Text = Array_GetValueByTag(infoMod, 0, _addonType & "-version_min")
        textboxTargetVersionMax.Text = Array_GetValueByTag(infoMod, 0, _addonType & "-version_max")
        comboboxType.Text = _addonType

        _pathDiff = Array_GetValueByTag(infoMod, 0, "path")

        _count = Array_GetPatchCount(infoMod, 0)

        If (_count = 0) Then Exit Sub

        For i As Integer = 0 To (_count - 1)

            _fileDiff = Array_GetValueByTag(infoMod, 0, "patch" & i & "-diff")
            _fileTarget = Array_GetValueByTag(infoMod, 0, "patch" & i & "-file")

            Dim _diff As String = Path.Combine(_pathDiff, _fileDiff)
            Dim _dest As String = Path.Combine(_tmpDir, _fileDiff)

            If (File.Exists(_dest)) Then File.Delete(_dest)
            If (File.Exists(_diff)) Then File.Copy(_diff, _dest)

            _data(0) = _fileDiff
            _data(1) = "File"
            _data(2) = Array_GetValueByTag(infoMod, 0, "patch" & i & "-original")
            _data(3) = Array_GetValueByTag(infoMod, 0, "patch" & i & "-modified")
            _data(4) = Array_GetValueByTag(infoMod, 0, "patch" & i & "-location")
            _data(5) = _fileTarget
            _data(6) = Array_GetValueByTag(infoMod, 0, "patch" & i & "-md5")
            _data(7) = _data(4) & "\" & _data(5)

            If (String_IsEmpty(_fileTarget)) Then _data(1) = "Directory"

            _item = New ListViewItem(_data)

            listviewPatchList.Items.Add(_item)

        Next

        Form_ListView_AutoResize(listviewPatchList)
    End Sub

    Private Sub buttonLocateType_Click(ByVal sender As Object, ByVal e As EventArgs) Handles buttonLocateType.Click

        Dim dialogPath As String
        Dim dir As String()
        Dim i As Integer
        Dim ext As String
        Dim output As String = Nothing

        dialogPath = Dialog_BrowseDirectory()

        If dialogPath = Nothing Then Exit Sub

        dir = Directory.GetFiles(Path.GetDirectoryName(dialogPath), SearchOption.TopDirectoryOnly)

        For i = 0 To (dir.Count - 1)

            ext = Path.GetExtension(dir(i))

            textboxTargetFileName.Text = Directory_GetParent(dir(i))
            textboxTargetLocation.Text = Path.GetDirectoryName(dir(i))

            If ext = "cs" Then

                output = "Plugin"

            ElseIf ext = "xml" Then

                output = "Profile"

            ElseIf ext = "dis" Then

                output = "Item Rule"

            End If

            If String_IsEmpty(output) = False Then

                comboboxType.Text = output

                Return

            End If

        Next

        comboboxType.Text = "Custom"
    End Sub

    Private Sub ModificationGeneratorToolStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs) _
        Handles menuShowModificationGenerator.Click

        _panelActive = panelGenerateModification

        Form_Resize()
    End Sub

    Private Sub radioTTFile_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs) _
        Handles radioTTFile.CheckedChanged

        If CType(sender, RadioButton).Checked Then

            textboxTargetFileName.Enabled = True

        End If
    End Sub

    Private Sub radioTTDirectory_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs) _
        Handles radioTTDirectory.CheckedChanged

        If CType(sender, RadioButton).Checked Then

            textboxTargetFileName.Enabled = False

        End If
    End Sub

    Private Sub buttonTargetLocation_Click(ByVal sender As Object, ByVal e As EventArgs) _
        Handles buttonTargetLocation.Click

        Dim _textbox As TextBox = textboxTargetLocation
        Dim _dialog As String

        If textboxTargetFileName.Enabled = True Then

            _dialog = Dialog_OpenFile()

            If _dialog Is Nothing Then Exit Sub

            If File.Exists(_dialog) Then
                _textbox.BackColor = Color.White
                textboxTargetFileName.BackColor = Color.White
            Else
                _textbox.BackColor = Color.Silver
                textboxTargetFileName.BackColor = Color.Silver
            End If

            _textbox.Text = String_ReplaceToKVP(Path.GetDirectoryName(_dialog), _textSubstitute)
            textboxTargetFileName.Text = Path.GetFileName(_dialog)

        Else

            _dialog = Dialog_BrowseDirectory()

            If _dialog Is Nothing Then Exit Sub

            If Directory.Exists(_dialog) Then
                _textbox.BackColor = Color.White
            Else
                _textbox.BackColor = Color.White
            End If

            textboxTargetLocation.Text = _dialog

        End If
    End Sub

    Private Sub buttonModificationSave_Click(ByVal sender As Object, ByVal e As EventArgs) _
        Handles buttonModificationSave.Click

        Dim dialog As String = Dialog_BrowseDirectory(My.Settings.FolderPatch(0))

        If dialog = Nothing Then Exit Sub

        Dim destPath As String = dialog

        Dim _copyFrom As String
        Dim _copyTo As String

        Dim addonType As String = comboboxType.Text

        If (String_IsEmpty(textboxPatchTitle.Text)) Or
           (String_IsEmpty(textboxPatchDescription.Text)) Or
           (String_IsEmpty(textboxPatchVersion.Text)) Or
           (String_IsEmpty(textboxPatchTitle.Text)) Or
           (String_IsEmpty(textboxPatchAuthor.Text)) Then

            Dim _Msg = New MsgBoxEx("Please complete filling out the required fields.", Me.Text, ,
                                    MsgBoxExImage.Exclamation)
            _Msg.SetButtons(New String() {"OK"}, New DialogResult() {DialogResult.Yes}, 1)
            _Msg.ShowDialog(Me)

            Exit Sub

        End If

        If String_IsEmpty(textboxPatchVersion.Text) Then
            dialog = Path.Combine(dialog, textboxPatchTitle.Text & ".dma")
            '
        Else
            dialog = Path.Combine(dialog,
                                  textboxPatchTitle.Text & " (v" & Replace(textboxPatchVersion.Text, ".", "") & ").dma")
        End If

        Dim xmlWriter As New XmlTextWriter(dialog, Encoding.UTF8)

        xmlWriter.WriteStartDocument(True)
        xmlWriter.Formatting = Formatting.Indented
        xmlWriter.Indentation = 2

        xmlWriter.WriteStartElement("patch_info")
        xmlWriter.WriteStartElement("patch")

        XML_CreateNode(xmlWriter, "addon-title", textboxPatchTitle.Text)
        XML_CreateNode(xmlWriter, "addon-description", textboxPatchDescription.Text)
        XML_CreateNode(xmlWriter, "addon-type", addonType)
        XML_CreateNode(xmlWriter, "addon-subtype", comboboxSubtype.Text)
        XML_CreateNode(xmlWriter, "addon-class", comboboxTargetClass.Text)
        XML_CreateNode(xmlWriter, "addon-version", textboxPatchVersion.Text)
        XML_CreateNode(xmlWriter, "addon-author", textboxPatchAuthor.Text)
        XML_CreateNode(xmlWriter, "addon-author_url", textboxPatchAuthorURL.Text)
        XML_CreateNode(xmlWriter, "addon-svn", textboxPatchSVN.Text)

        For i As Integer = 0 To (listviewPatchList.Items.Count - 1)

            XML_CreateNode(xmlWriter, "patch" & i & "-diff", listviewPatchList.Items(i).SubItems(0).Text)
            XML_CreateNode(xmlWriter, "patch" & i & "-original", listviewPatchList.Items(i).SubItems(2).Text)
            XML_CreateNode(xmlWriter, "patch" & i & "-modified", listviewPatchList.Items(i).SubItems(3).Text)
            XML_CreateNode(xmlWriter, "patch" & i & "-md5", listviewPatchList.Items(i).SubItems(6).Text)
            XML_CreateNode(xmlWriter, "patch" & i & "-location", listviewPatchList.Items(i).SubItems(4).Text)
            XML_CreateNode(xmlWriter, "patch" & i & "-file", listviewPatchList.Items(i).SubItems(5).Text)

            _copyFrom = Path.Combine(_tmpDir, listviewPatchList.Items(i).SubItems(0).Text)
            _copyTo = Path.Combine(destPath, listviewPatchList.Items(i).SubItems(0).Text)

            If (File.Exists(_copyFrom)) Then

                If (File.Exists(_copyTo)) Then

                    File.Delete(_copyTo)

                End If

                File.Copy(_copyFrom, _copyTo)

            End If

        Next

        XML_CreateNode(xmlWriter, addonType.ToLower & "-name", textboxTargetName.Text)
        XML_CreateNode(xmlWriter, addonType.ToLower & "-version_min", textboxTargetVersionMin.Text)
        XML_CreateNode(xmlWriter, addonType.ToLower & "-version_max", textboxTargetVersionMax.Text)

        xmlWriter.WriteEndElement() 'patch
        xmlWriter.WriteEndElement() 'patch-info
        xmlWriter.WriteEndDocument()
        xmlWriter.Close()

        Dim _MsgSaved =
                New MsgBoxEx(
                    "Patch saved saved. If you would like to use this patch, ensure you add it to your Modifications directory list - or copy it to a folder currently in your Modifications directory list.",
                    Me.Text, , MsgBoxExImage.Check)
        _MsgSaved.SetButtons(New String() {"OK"}, New DialogResult() {DialogResult.Yes}, 1)
        _MsgSaved.ShowDialog(Me)

        _panelActive = panelModifications

        Form_Resize()
    End Sub

    Private Sub buttonAddPatch_Click(ByVal sender As Object, ByVal e As EventArgs) Handles buttonAddPatch.Click

        Dim _fileDiff As String
        Dim _type As String
        Dim _original As String
        Dim _modified As String
        Dim _pathTarget As String
        Dim _fileTarget As String
        Dim _md5Diff As String

        Dim _create As Boolean

        Dim _data(7) As String
        Dim _item As ListViewItem

        _fileDiff = textboxPatchFileName.Text
        _fileTarget = textboxTargetFileName.Text
        _pathTarget = textboxTargetLocation.Text
        _type =
            groupboxPatchGenerationTarget.Controls.OfType(Of RadioButton)().Where(Function(r) r.Checked = True).
                FirstOrDefault.Text
        _original = textboxDiffOriginal.Text
        _modified = textboxDiffModified.Text

        If Not (_pathTarget.Contains("{demonbuddy-dir}") Or _pathTarget.Contains("{profile-dir}")) Then

            Dim _Msg =
                    New MsgBoxEx("Target location must contain a keyword for directory placement." & vbCrLf & vbCrLf &
                                 "Examples:" & vbCrLf & vbCrLf &
                                 "{demonbuddy-dir}  ---  This would be replaced with your Demonbuddy directory specified in your settings." &
                                 vbCrLf &
                                 "{profile-dir}  ---  This would be replaced with your Profiles directory specified in your settings." &
                                 vbCrLf &
                                 "{itemrules-dir}  ---  This would be replaced with your Item Rules directory specified in your settings." &
                                 vbCrLf &
                                 "{patch-dir}  ---  This would be replaced with your Utilties directory specified in your settings." &
                                 vbCrLf & vbCrLf &
                                 "Correct Target Location: {demonbuddy-dir}\Plugins\Trinity\Combat\Abilities\BarbarianCombat.cs" &
                                 vbCrLf &
                                 "Incorrect Target Location: C:\Demonbuddy\Plugins\Trinity\Combat\Abilities\BarbarianCombat.cs" &
                                 vbCrLf & vbCrLf &
                                 "You can also have DBMA search for the file in a directory and it's sub-directories by inputting just the root directory (Example: {demonbuddy-dir}).",
                                 Me.Text, , MsgBoxExImage.Exclamation)
            _Msg.SetButtons(New String() {"OK"}, New DialogResult() {DialogResult.Yes}, 1)
            _Msg.ShowDialog(Me)

            Exit Sub

        End If

        If (_type = "File") And (String_IsEmpty(_fileTarget)) Then

            Dim _Msg = New MsgBoxEx("Please specify target file.", Me.Text, , MsgBoxExImage.Exclamation)
            _Msg.SetButtons(New String() {"OK"}, New DialogResult() {DialogResult.Yes}, 1)
            _Msg.ShowDialog(Me)

            Exit Sub

        End If

        _create = Diff_Create(Path.Combine(_tmpDir, _fileDiff), _original, _modified)

        If _create = True Then

            _md5Diff = File_MD5(Path.Combine(_tmpDir, _fileDiff))

            _data(0) = _fileDiff
            _data(1) = _type
            _data(2) = _original
            _data(3) = _modified
            _data(4) = _pathTarget
            _data(5) = _fileTarget
            _data(6) = _md5Diff
            _data(7) = _data(4) & "\" & _data(5)

            _item = New ListViewItem(_data)

            listviewPatchList.Items.Add(_item)

            Form_ListView_AutoResize(listviewPatchList)

        Else

            Dim _Msg = New MsgBoxEx("There was an error writing the patch. Please try again.", Me.Text, ,
                                    MsgBoxExImage.Exclamation)
            _Msg.SetButtons(New String() {"OK"}, New DialogResult() {DialogResult.Yes}, 1)
            _Msg.ShowDialog(Me)

        End If
    End Sub

    Private Sub buttonPatchRemove_Click(ByVal sender As Object, ByVal e As EventArgs) Handles buttonPatchRemove.Click

        For i As Integer = 0 To (listviewPatchList.Items.Count - 1)

            If listviewPatchList.Items(i).Selected Then

                Dim _fileName As String = listviewPatchList.Items(i).SubItems(0).Text
                Dim _path As String = Path.Combine(_tmpDir, _fileName)

                If File.Exists(_path) Then File.Delete(_path)

                listviewPatchList.Items.RemoveAt(i)

            End If

        Next
    End Sub

    Private Sub listviewPatchList_SelectedIndexChanged(sender As Object, e As EventArgs) _
        Handles listviewPatchList.SelectedIndexChanged

        Dim _item As ListViewItem
        Dim _patchFileName As String
        Dim _patchOriginal As String
        Dim _patchModified As String
        Dim _patchTargetLocation As String
        Dim _patchTargetFileName As String

        _item = listviewPatchList.SelectedItems.Item(0)

        _patchFileName = _item.SubItems(0).Text
        _patchOriginal = _item.SubItems(2).Text
        _patchModified = _item.SubItems(3).Text
        _patchTargetLocation = _item.SubItems(4).Text
        _patchTargetFileName = _item.SubItems(5).Text

        If String_IsEmpty(Path.GetFileName(_patchTargetFileName)) = False Then

            radioTTFile.Checked = True
            radioTTDirectory.Checked = False

            textboxTargetFileName.Enabled = True

        Else

            radioTTFile.Checked = False
            radioTTDirectory.Checked = True

            textboxTargetFileName.Enabled = False

            _patchTargetLocation = _patchTargetLocation
            _patchTargetFileName = Nothing

        End If

        textboxPatchFileName.Text = _patchFileName
        textboxDiffOriginal.Text = _patchOriginal
        textboxDiffModified.Text = _patchModified
        textboxTargetLocation.Text = _patchTargetLocation
        textboxTargetFileName.Text = _patchTargetFileName

        If (File.Exists(_patchOriginal) And File.Exists(_patchModified)) Then
            buttonPatchUpdate.Enabled = True
        Else
            buttonPatchUpdate.Enabled = False
        End If
    End Sub

    Private Sub buttonModificationReset_Click(sender As Object, e As EventArgs) Handles buttonModificationReset.Click

        radioTTFile.Checked = True
        radioTTDirectory.Checked = False

        comboboxType.Text = ""
        comboboxSubtype.Text = ""

        textboxPatchTitle.Clear()
        textboxPatchDescription.Clear()
        textboxPatchAuthor.Clear()
        textboxPatchAuthorURL.Clear()
        textboxCName.Clear()
        textboxTargetName.Clear()
        textboxTargetVersionMin.Clear()
        textboxTargetVersionMax.Clear()

        listviewPatchList.Items.Clear()

        textboxPatchFileName.Clear()
        textboxDiffOriginal.Clear()
        textboxDiffModified.Clear()
        textboxTargetLocation.Clear()
        textboxTargetFileName.Clear()
    End Sub

    Private Sub textboxPatchFileName_LostFocus(sender As Object, e As EventArgs) Handles textboxPatchFileName.LostFocus

        Dim _tmp As String = textboxPatchFileName.Text

        If (_tmp Is Nothing) Then Exit Sub

        If (String_Substring(_tmp, (_tmp.Length - 6), 6) <> ".patch") Then _tmp = _tmp & ".patch"

        textboxPatchFileName.Text = _tmp
    End Sub

    Private Sub textboxPatchVersion_LostFocus(sender As Object, e As EventArgs) Handles textboxPatchVersion.LostFocus

        Version_Check(sender)
    End Sub

    Private Sub textboxTargetVersionMin_LostFocus(sender As Object, e As EventArgs) _
        Handles textboxTargetVersionMin.LostFocus

        Version_Check(sender)
    End Sub

    Private Sub textboxTargetVersionMax_LostFocus(sender As Object, e As EventArgs) _
        Handles textboxTargetVersionMax.LostFocus

        Version_Check(sender)
    End Sub

    Private Sub textboxAVersion_LostFocus(sender As Object, e As EventArgs) Handles textboxAVersion.LostFocus

        Version_Check(sender)
    End Sub

    Public Sub DBMA_Mods_Refresh_Status(Optional optRefresh As Boolean = False,
                                        Optional patchIndex As Integer? = Nothing)

        Dim _idxStart As Integer = 0
        Dim _idxEnd As Integer = (listviewextendedModifications.Items.Count - 1)

        Dim _subitemStatus As ListViewItem.ListViewSubItem

        Dim _patchName As ListViewItem.ListViewSubItem
        Dim _patchID As Integer?
        Dim _patchStatus As String

        If (patchIndex IsNot Nothing) Then

            _idxStart = patchIndex
            _idxEnd = patchIndex

        End If

        For i As Integer = _idxStart To _idxEnd

            Application.DoEvents()

            Dim _current As Integer = (i - _idxStart)
            Dim _max As Integer = ((_idxEnd - _idxStart) + 1)

            Form_ProgressBar_Update("Checking Modifications Current Status (" & _current & "/" & _max & ")...", _current,
                                    , _max)

            _subitemStatus = listviewextendedModifications.Items(i).SubItems(5)

            If _subitemStatus.Text.Contains("Processing") Then

                _patchName = listviewextendedModifications.Items(i).SubItems(0)
                _patchID = Array_GetIDByValue(infoPatch, "addon-title", _patchName.Text)

                _patchStatus = DBMA_Mod_Refresh_Status(_patchID, optRefresh)

                If (_patchStatus = "Applied!") Or (_patchStatus = "Ready") Then

                    listviewextendedModifications.Items(i).BackColor = Color.Gainsboro
                    _subitemStatus.ForeColor = Color.Black

                Else

                    listviewextendedModifications.Items(i).BackColor = Color.White
                    _subitemStatus.ForeColor = Color.DarkBlue

                End If

                _subitemStatus.Text = _patchStatus

            End If

        Next

        Form_ListView_AutoResize(listviewextendedModifications)

        Form_ProgressBar_Update("Checking Modifications Current Status (Complete)", 0, 0, 1)
    End Sub

    Public Sub DBMA_Mods_Refresh_Update(Optional patchIndex As Integer? = Nothing)

        Dim _idxStart As Integer = 0
        Dim _idxEnd As Integer = (listviewextendedModifications.Items.Count - 1)
        Dim _subitemUpdate As ListViewItem.ListViewSubItem

        Dim _hasUpdate As en_resultUpdateCheck

        Dim _patchName As ListViewItem.ListViewSubItem
        Dim _patchID As Integer?

        If (patchIndex IsNot Nothing) Then

            _idxStart = patchIndex
            _idxEnd = patchIndex

        End If

        For i As Integer = _idxStart To _idxEnd

            Application.DoEvents()

            Dim _current As Integer = (i - _idxStart)
            Dim _max As Integer = ((_idxEnd - _idxStart) + 1)

            Form_ProgressBar_Update("Checking For Modification Updates... (" & _current & "/" & _max & ")...", _current,
                                    , _max)

            _subitemUpdate = listviewextendedModifications.Items(i).SubItems(6)

            If _subitemUpdate.Text.Contains("Processing") Then

                _patchName = listviewextendedModifications.Items(i).SubItems(0)
                _patchID = Array_GetIDByValue(infoPatch, "addon-title", _patchName.Text)

                _hasUpdate = DBMA_Mod_Refresh_Update(_patchID)

                If _hasUpdate = en_resultUpdateCheck.UpdateAvailable Then

                    _subitemUpdate.ForeColor = Color.DarkRed
                    _subitemUpdate.Text = "Update Available"

                ElseIf _hasUpdate = en_resultUpdateCheck.UpToDate Then

                    _subitemUpdate.ForeColor = Color.Black
                    _subitemUpdate.Text = "Latest Version"

                ElseIf _hasUpdate = en_resultUpdateCheck.NoSvnPath Then

                    _subitemUpdate.ForeColor = Color.Black
                    _subitemUpdate.Text = String.Empty

                Else

                    _subitemUpdate.ForeColor = Color.Red
                    _subitemUpdate.Text = "Error"

                End If

                Array_SetValueByTag(infoPatch, i, "status-update", _hasUpdate)

            End If

        Next

        Form_ListView_AutoResize(listviewextendedModifications)

        Form_ProgressBar_Update("Checking For Modification Updates... (Complete)", 0, 0, 1)
    End Sub

    Private Sub frmMain_Shown(sender As Object, e As EventArgs) Handles Me.Shown

        DBMA_AfterWizard()

    End Sub

    Private Sub timerProcessingText_Tick(sender As Object, e As EventArgs) Handles timerProcessingText.Tick

        Dim _patchStatus As ListViewItem.ListViewSubItem
        Dim _patchUpdate As ListViewItem.ListViewSubItem
        Dim _count As Integer = String_CharCount(_processingText, ".")
        Dim _updated As Boolean = False

        If (_triggerReadMods) And (frmSettings.Visible = False) Then

            _triggerReadMods = False

            DBMA_Mods_Refresh()
            DBMA_Menus_Refresh()

            _triggerRefresh = True

        End If

        If (_triggerRefresh) And (frmSettings.Visible = False) Then

            _triggerRefresh = False

            If (bw.IsBusy = False) Then

                bw.RunWorkerAsync()

            End If

        End If

        If _count < 3 Then
            _processingText = _processingText & "."
        Else
            _processingText = "Processing"
        End If

        listviewextendedModifications.BeginUpdate()

        For i As Integer = 0 To (listviewextendedModifications.Items.Count - 1)

            _patchStatus = listviewextendedModifications.Items(i).SubItems(5)
            _patchUpdate = listviewextendedModifications.Items(i).SubItems(6)

            If _patchStatus.Text.Contains("Processing") Then
                _updated = True
                _patchStatus.Text = _processingText
            End If

            If _patchUpdate.Text.Contains("Processing") Then
                _updated = True
                _patchUpdate.Text = _processingText
            End If

        Next

        listviewextendedModifications.EndUpdate()

        If _updated = False Then timerProcessingText.Stop()
    End Sub

    Private Sub menuApplyMod_Click(sender As Object, e As EventArgs) Handles menuApplyMod.Click

        Dim _index As Integer = _modIndex

        For i As Integer = 0 To (listviewextendedModifications.Items.Count - 1)

            If i = _index Then

                listviewextendedModifications.Items(i).Checked = True

            Else

                listviewextendedModifications.Items(i).Checked = False

            End If

        Next

        Call buttonApply_Click(sender, New EventArgs())
    End Sub

    Private Sub menuUpdateMod_Click(sender As Object, e As EventArgs) Handles menuUpdateMod.Click

        Dim _index As Integer = _modIndex
        Dim _title As String = listviewextendedModifications.Items(_index).SubItems(0).Text
        Dim _id As Integer? = Array_GetIDByValue(infoPatch, "addon-title", _title)
        Dim _result As Boolean?

        _result = DBMA_Mod_Update(_id)

        If _result = True Then

            _triggerReadMods = True

            timerProcessingText.Start()

        ElseIf _result = False Then

            Dim _Msg = New MsgBoxEx("Error updating modification from SVN.", Me.Text, , MsgBoxExImage.Exclamation)
            _Msg.SetButtons(New String() {"OK"}, New DialogResult() {DialogResult.Yes}, 1)
            _Msg.ShowDialog(Me)

        Else

            Dim _Msg = New MsgBoxEx("Internal error. Please restart and try again.", Me.Text, ,
                                    MsgBoxExImage.Exclamation)
            _Msg.SetButtons(New String() {"OK"}, New DialogResult() {DialogResult.Yes}, 1)
            _Msg.ShowDialog(Me)

        End If
    End Sub

    Public Function Diff_InterpretStatus(ByVal patchArray() As xmlInformation, ByVal patchIndex As Integer) As String

        Dim countSuccessWithChanges As Integer
        Dim countSuccess As Integer
        Dim countAlreadyPatched As Integer
        Dim countFailure As Integer
        Dim countExeNotFound As Integer
        Dim countExeLockup As Integer
        Dim countExeError As Integer
        Dim countPatchNotFound As Integer
        Dim countVerboseNotFound As Integer
        Dim countTargetNotFound As Integer
        Dim countUnknown As Integer

        Dim _count As Integer
        Dim _tmp As String
        Dim _result As en_resultPatch()

        _count = Array_GetPatchCount(patchArray, patchIndex)

        ReDim _result(_count - 1)

        For i As Integer = 0 To (_count - 1)

            _tmp = Array_GetValueByTag(patchArray, patchIndex, "status-" & i)

            If (IsNumeric(_tmp)) Then _result(i) = CInt(_tmp)

        Next

        For i As Integer = 0 To (_result.Count - 1)

            If _result(i) = en_resultPatch.AlreadyPatched Then countAlreadyPatched = countAlreadyPatched + 1
            If _result(i) = en_resultPatch.ExeError Then countExeError = countExeError + 1
            If _result(i) = en_resultPatch.ExeLockup Then countExeLockup = countExeLockup + 1
            If _result(i) = en_resultPatch.ExeNotFound Then countExeNotFound = countExeNotFound + 1
            If _result(i) = en_resultPatch.Failure Then countFailure = countFailure + 1
            If _result(i) = en_resultPatch.PatchNotFound Then countPatchNotFound = countPatchNotFound + 1
            If _result(i) = en_resultPatch.Success Then countSuccess = countSuccess + 1
            If _result(i) = en_resultPatch.SuccessWithChanges Then countSuccessWithChanges = countSuccessWithChanges + 1
            If _result(i) = en_resultPatch.TargetNotFound Then countTargetNotFound = countTargetNotFound + 1
            If _result(i) = en_resultPatch.Unknown Then countUnknown = countUnknown + 1
            If _result(i) = en_resultPatch.VerboseNotFound Then countVerboseNotFound = countVerboseNotFound + 1

        Next

        If countExeNotFound > 0 Then Return "Patcher Not Found"
        If countExeError > 0 Then Return "Patcher Error"
        If countExeLockup > 0 Then Return "Patcher Lockup"
        If countPatchNotFound > 0 Then Return "Patch Not Found"
        If countTargetNotFound > 0 Then Return "Target Not Found"
        If countVerboseNotFound > 0 Then Return "Cannot Read Output"
        If countUnknown > 0 Then Return "Unknown Error"
        If countFailure > 0 Then Return "Not Ready"

        If (countAlreadyPatched > 0) And
           (countSuccess = 0) And
           (countSuccessWithChanges = 0) Then

            Return "Applied!"

        End If

        If (countSuccessWithChanges > 0) Then

            Return "Ready (with Offset)"

        End If

        Return "Ready"
    End Function

    Public Function Patch_InterpretStatus(ByVal patchArray() As xmlInformation, ByVal patchIndex As String,
                                          Optional ByRef patchUpdateStatus As Boolean = True) As String

        Dim patchCount As Integer
        Dim _tmpResult As String
        Dim _patchResults() As en_resultPatch
        Dim i As Integer

        Dim resultPatched As Integer = 0
        Dim resultFailure As Integer = 0
        Dim resultTargetNotFound As Integer = 0
        Dim resultSuccess As Integer = 0
        Dim resultSuccessAlt As Integer = 0
        Dim resultUnknown As Integer = 0
        Dim resultPatchNotFound As Integer = 0
        Dim resultVerboseNotFound As Integer = 0

        patchCount = Array_GetPatchCount(patchArray, patchIndex)

        ReDim _patchResults(patchCount - 1)

        For i = 0 To (patchCount - 1)

            Application.DoEvents()

            _tmpResult = Array_GetValueByTag(patchArray, patchIndex, "status-" & i)

            If IsNumeric(_tmpResult) = True Then

                _patchResults(i) = CInt(_tmpResult)

            Else

                Return Nothing

            End If

        Next

        For i = 0 To (_patchResults.Count - 1)

            If _patchResults(i) = en_resultPatch.AlreadyPatched Then
                resultPatched = resultPatched + 1
            ElseIf _patchResults(i) = en_resultPatch.Failure Then
                resultFailure = resultFailure + 1
            ElseIf _patchResults(i) = en_resultPatch.TargetNotFound Then
                resultTargetNotFound = resultTargetNotFound + 1
            ElseIf _patchResults(i) = en_resultPatch.Success Then
                resultSuccess = resultSuccess + 1
            ElseIf _patchResults(i) = en_resultPatch.SuccessWithChanges Then
                resultSuccessAlt = resultSuccessAlt + 1
            ElseIf _patchResults(i) = en_resultPatch.Unknown Then
                resultUnknown = resultUnknown + 1
            ElseIf _patchResults(i) = en_resultPatch.PatchNotFound Then
                resultPatchNotFound = resultPatchNotFound + 1
            ElseIf _patchResults(i) = en_resultPatch.VerboseNotFound Then
                resultVerboseNotFound = resultVerboseNotFound + 1
            ElseIf _patchResults(i) = en_resultPatch.ExeNotFound Then
                Return "Patch.exe Not Found"
            End If

        Next

        If _
            (resultFailure = 0) And (resultTargetNotFound = 0) And (resultUnknown = 0) And (resultPatchNotFound = 0) And
            (resultVerboseNotFound = 0) Then

            If (resultPatched > 0) And (resultSuccess = 0) And (resultSuccessAlt = 0) Then

                If patchUpdateStatus = True Then _
                    Array_SetValueByTag(patchArray, patchIndex, "status", "Already Applied")

                Return "Already Applied"

            ElseIf (resultPatched > 0) And ((resultSuccess > 0) Or (resultSuccessAlt > 0)) Then

                If patchUpdateStatus = True Then _
                    Array_SetValueByTag(patchArray, patchIndex, "status", "Partially Applied")

                Return "Partially Applied"

            Else

                If patchUpdateStatus = True Then Array_SetValueByTag(patchArray, patchIndex, "status", "Not Applied")

                Return "Not Applied"

            End If
        Else
            If (resultFailure > 0) Then

                If patchUpdateStatus = True Then Array_SetValueByTag(patchArray, patchIndex, "status", "Cannot Apply")

                Return "Cannot Apply"

            ElseIf (resultTargetNotFound > 0) Then

                If patchUpdateStatus = True Then _
                    Array_SetValueByTag(patchArray, patchIndex, "status", "Cant Find Target/s")

                Return "Target/s Not Found"

            ElseIf (resultPatchNotFound > 0) Then

                If patchUpdateStatus = True Then _
                    Array_SetValueByTag(patchArray, patchIndex, "status", "Patch/s Not Found")

                Return "Patch/s Not Found"

            ElseIf (resultVerboseNotFound > 0) Then

                If patchUpdateStatus = True Then _
                    Array_SetValueByTag(patchArray, patchIndex, "status", "Output Not Found")

                Return "Output Not Found"

            Else

                If patchUpdateStatus = True Then Array_SetValueByTag(patchArray, patchIndex, "status", "Unknown Error")

                Return "Unknown Error"

            End If

        End If
    End Function

    Private Sub buttonPatchUpdate_Click(sender As Object, e As EventArgs) Handles buttonPatchUpdate.Click

        Dim _selected As ListView.SelectedListViewItemCollection = listviewPatchList.SelectedItems
        Dim _item As ListViewItem

        For Each _item In _selected

            Dim _fileName As String = _item.SubItems(0).Text
            Dim _path As String = Path.Combine(_tmpDir, _fileName)

            If File.Exists(_path) Then File.Delete(_path)

            listviewPatchList.Items.RemoveAt(_item.Index)

        Next

        Call buttonAddPatch_Click(sender, New EventArgs())
    End Sub

    Private Sub buttonOriginalSource_Click(sender As Object, e As EventArgs) Handles buttonOriginalSource.Click

        Dim _textbox As TextBox = textboxDiffOriginal

        If textboxTargetFileName.Enabled = True Then

            _textbox.Text = Dialog_OpenFile()

            If _textbox.Text Is Nothing Then Exit Sub

            If File.Exists(_textbox.Text) Then
                _textbox.BackColor = Color.White
            Else
                _textbox.BackColor = Color.Silver
            End If

        Else

            _textbox.Text = Dialog_BrowseDirectory()

            If _textbox.Text Is Nothing Then Exit Sub

            If Directory.Exists(_textbox.Text) Then
                _textbox.BackColor = Color.White
            Else
                _textbox.BackColor = Color.Silver
            End If

        End If
    End Sub

    Private Sub buttonModifiedSource_Click(sender As Object, e As EventArgs) Handles buttonModifiedSource.Click

        Dim _textbox As TextBox = textboxDiffModified

        If textboxTargetFileName.Enabled = True Then

            _textbox.Text = Dialog_OpenFile()

            If _textbox.Text Is Nothing Then Exit Sub

            If File.Exists(_textbox.Text) Then
                _textbox.BackColor = Color.White
            Else
                _textbox.BackColor = Color.Silver
            End If

        Else

            _textbox.Text = Dialog_BrowseDirectory()

            If _textbox.Text Is Nothing Then Exit Sub

            If Directory.Exists(_textbox.Text) Then
                _textbox.BackColor = Color.White
            Else
                _textbox.BackColor = Color.Silver
            End If

        End If
    End Sub

    Private Sub bw_DoWork(sender As Object, e As DoWorkEventArgs) Handles bw.DoWork

        Dim _refresh As backgroundRefresh

        _refresh = New backgroundRefresh(AddressOf DBMA_Refresh_All)

        Invoke(_refresh)
    End Sub

    Private Sub bw_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles bw.RunWorkerCompleted

        Form_ProgressBar_Update("Modification Status Update (Complete)", 1, 0, 1)
    End Sub

    Private Sub menuRescan_Click(sender As Object, e As EventArgs) Handles menuRescan.Click

        _triggerReadMods = True

        timerProcessingText.Start()
    End Sub

    Private Sub menuHelp_Click(sender As Object, e As EventArgs) Handles menuHelp.Click

        Process.Start("http://www.thebuddyforum.com/members/262403-prettypia.html")
    End Sub

    Private Sub buttonExport_Click(sender As Object, e As EventArgs) Handles buttonExport.Click
    End Sub
End Class